import React, { useState } from 'react';
import { history, connect } from 'umi';
import { Card, Button, Form } from 'antd';
import { Col, Row, Tag, Tooltip, Space, notification } from 'antd';
import DrawerCondition from '@/components/DrawerCondition';
import FormCondition from '@/components/FormCondition';
import SelectModel from './../SelectModel';
import { TeamOutlined, QuestionCircleOutlined } from '@ant-design/icons';
import Uploadjs from '@/utils/aliOssUpload';
import { useEffect } from 'react';
const CodeInfo = (props) => {
  const { dispatch, visible = {}, onClose, handleCallback, loading, searchLoading } = props;
  const [modelVisible, setModelVisible] = useState(false);
  const [data, setData] = useState(null);
  const { show = false, detail = {} } = visible;
  const [searChList, setSearchList] = useState({});
  const [checkRadio, setCheckRadio] = useState(false);
  const { id } = detail;
  const [form] = Form.useForm();
  // 新增修改 传id修改 不传id新增
  const fetchRoleEdit = () => {
    form.validateFields().then(async (values) => {
      const { image } = values;
      const { id } = detail;
      const img = (await Uploadjs(image)) || [];
      if (!data) {
        return notification.warn({
          message: '警告提示',
          description: '请选择群后提交',
        });
      } else {
        dispatch({
          type: 'system/fakeInsertChatCode',
          payload: {
            ...values,
            image: img.toString(),
            chatNameList: [data.chatName].toString(),
            chatIdList: [data.chatId].toString(),
            id,
          },
          callback: () => {
            onClose();
            handleCallback();
          },
        });
      }
    });
  };
  useEffect(() => {
    if (show) {
      if (detail.id) {
        setData({
          chatId: detail.chatIdList,
          chatName: detail.chatNameList,
        });
      }
    } else {
      setSearchList({});
      setCheckRadio(false);
      setData(null);
    }
  }, [show]);
  useEffect(() => {
    fetchSearchList();
  }, []);
  const modalProps = {
    title: `${id ? '修改' : '新增'}`,
    visible: show,
    onClose,
    destroyOnClose: true,
    footer: (
      <Button type="primary" loading={loading} onClick={fetchRoleEdit}>
        确定
      </Button>
    ),
  };
  const fetchSearchList = () => {
    dispatch({
      type: 'system/fetchChatCodePage',

      callback: (e = {}) => {
        setSearchList(e);
      },
    });
  };
  const ChatNameSet = (props) => {
    const { data = {} } = props;
    const { chatId, chatName } = data || {};
    if (chatId) {
      return (
        <Row style={{ marginBottom: 24 }}>
          <Col offset={6}>
            <Tag icon={<TeamOutlined />} color="#55acee">
              {chatName}
            </Tag>
            <Button
              type="link"
              onClick={() => {
                setModelVisible({ show: true, details: data });
              }}
            >
              修改
            </Button>
          </Col>
        </Row>
      );
    } else {
      return (
        <Row style={{ marginBottom: 24 }}>
          <Col offset={6} gutter={[24, 24]}>
            <Button
              onClick={() => {
                setModelVisible({ show: true, details: data });
              }}
            >
              选择群聊
            </Button>
          </Col>
        </Row>
      );
    }
  };
  const filterList = (list) => {
    return list.map((item) => {
      const { desc, value } = item;
      return {
        name: desc,
        value,
      };
    });
  };
  const { channelList = [], ideaList = [], mediumList = [], planList = [] } = searChList;
  const formItems = [
    {
      label: '活码名称',
      name: 'codeName',
    },
    {
      label: '活码类型',
      name: 'codeType',
      type: 'radio',
      select: {
        normal: '普通群',
        marketing: '营销群',
      },
      onChange: (e) => {
        setCheckRadio(e.target.value);
      },
    },
    {
      label: '渠道类型',
      name: 'channelType',
      loading: searchLoading,
      type: 'select',
      select: filterList(channelList),
      visible: checkRadio === 'marketing',
    },
    {
      label: '媒介类型',
      name: 'mediumType',
      loading: searchLoading,
      type: 'select',
      select: filterList(mediumList),
      visible: checkRadio === 'marketing',
      rules: [{ required: false }],
    },
    {
      label: '计划id',
      name: 'planId',
      loading: searchLoading,
      type: 'select',
      select: filterList(planList),
      visible: checkRadio === 'marketing',
      rules: [{ required: false }],
    },
    {
      label: '创意id',
      name: 'ideaId',
      loading: searchLoading,
      type: 'select',
      select: filterList(ideaList),
      visible: checkRadio === 'marketing',
      rules: [{ required: false }],
    },

    {
      label: '设置活码头像',
      name: 'image',
      type: 'upload',
      maxFile: 1,
      extra: '可上传自定义图片用于客户展示图标',
    },
    {
      type: 'noForm',
      rules: [{ required: false }],
      formItem: <ChatNameSet data={data}></ChatNameSet>,
    },

    {
      label: '群前缀名称',
      name: 'roomBaseName',
    },
    {
      label: '群后缀',
      type: 'number',
      max: 999,
      addonBefore: (
        <Tooltip
          placement="topLeft"
          title={
            '举例：自动创建的第一个群，群名为“销售客服群10”；那么自动创建的第二个群，群名为“销售客服群11”，依次类推'
          }
        >
          <QuestionCircleOutlined />
        </Tooltip>
      ),
      name: 'roomBaseId',
    },
  ];

  return (
    <>
      <DrawerCondition {...modalProps}>
        <FormCondition form={form} formItems={formItems} initialValues={detail}></FormCondition>
      </DrawerCondition>
      <SelectModel
        onClose={() => {
          setModelVisible(false);
        }}
        onOk={(e) => setData(e)}
        visible={modelVisible}
      ></SelectModel>
    </>
  );
};
export default connect(({ system, loading }) => ({
  loading: loading.models.system,
  searchLoading: loading.effects['system/fetchChatCodePage'],
}))(CodeInfo);
